const express=require('express')
const http=require('http')
const app=express()
const port=3000


const server=http.createServer(app)
const {Server}=require('socket.io')
const io=new Server(server)
const clients=[]
app.get('/',(req,res)=>{
    res.sendFile(__dirname+'/index.html')
})

io.on('connection',(socket)=>{
    console.log('a user connected')
    // socket.broadcast.emit('chat message','发给其它从的消息')
    socket.on('chat message',data=>{
        io.emit('chat message',data)
    })
    socket.on('disconnect',()=>{
        const index=clients.findIndex(item=>item===socket)
        if(index!==-1){
            clients.splice(index,1)
        }
    })
})
server.listen(port,()=>{
    console.log(`running at http://localhost:${port}`)
})
